<template>
  <div class="cms-channel-container layout-padding">
    <el-card shadow="hover" class="layout-padding-auto">
      <div class="cms-channel-search mb15">
        <el-tree-select
            v-model="state.search.orgId"
            :data="state.sysOrgData"
            :render-after-expand="true"
            :default-expanded-keys="defaultExpandedKeys"
            style="width: 500px"
            check-strictly
            filterable
            @change="orgChange"
        />
        <el-button size="default" type="success" class="ml10" @click="onOpenAdd('add')">
          <el-icon>
            <ele-FolderAdd/>
          </el-icon>
          新增栏目
        </el-button>
      </div>
      <el-table
          :data="state.tableData.data"
          v-loading="state.tableData.loading"
          style="width: 100%"
          row-key="id"
          :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
          :default-expand-all="true"
          max-height="700"
          stripe
      >
        <el-table-column prop="label" label="栏目名称" show-overflow-tooltip width="300"></el-table-column>
        <el-table-column prop="orderNo" label="排序" show-overflow-tooltip width="180">
          <!--					<template #default="scope">-->
          <!--						{{ scope.$index }}-->
          <!--					</template>-->
        </el-table-column>
        <el-table-column prop="isDelete" label="状态" show-overflow-tooltip width="200">
          <template #default="scope">
            <el-tag type="success" v-if="scope.row.isDelete==0">启用</el-tag>
            <el-tag type="info" v-else>禁用</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="gmtCreate" label="创建时间" show-overflow-tooltip width="200"></el-table-column>
        <el-table-column prop="gmtModified" label="修改时间" show-overflow-tooltip width="200"></el-table-column>
				<el-table-column label="操作" show-overflow-tooltip >
					<template #default="scope">
<!--						<el-button size="small" text type="primary" @click="onOpenAdd('add')">新增</el-button>-->
						<el-button size="small" type="primary" @click="onOpenEdit('edit', scope.row)">修改</el-button>
						<el-button size="small" type="danger" @click="onTableRowDel(scope.row)" :disabled="scope.row.children.length != 0">删除</el-button>
					</template>
				</el-table-column>
			</el-table>
		</el-card>
		<channelDialog ref="channelDialogRef" @refresh="getTableData()" :orgId="state.search.orgId" :orgTree="state.sysOrgData"/>
	</div>
</template>

<script setup lang="ts" name="cmsChannelScript">
import {defineAsyncComponent, ref, reactive, onMounted} from 'vue';
import {ElMessageBox, ElMessage} from 'element-plus';
import {useChannelApi} from "/@/api/cms/channel";
const {channelTree, removeById} = useChannelApi();
import {systemApi} from "/@/api/system";
const {orgTree, orgAreaTree} = systemApi();
// 引入组件
const channelDialog = defineAsyncComponent(() => import('/@/views/cms/channel/dialog.vue'));

// 定义变量内容
const channelDialogRef = ref();
const defaultExpandedKeys = ref<string[]>([]); // 新增默认展开的节点
const state = reactive({
  search: {
    orgId: '',
  },
  sysOrgData: [],
  tableData: {
    data: [],
    total: 0,
    loading: false,
    param: {
      pageNum: 1,
      pageSize: 2100,
    },
  },
});

// 在加载数据时设置默认展开的节点
const loadOrgTree = async () => {
  const res = await orgAreaTree();
  if (res.status === 200) {
    state.sysOrgData = res.data;
    // 设置默认展开的节点为第一个节点的ID
    if (state.sysOrgData.length > 0) {
      defaultExpandedKeys.value = [state.sysOrgData[0].id];
    }
  }
};

const orgChange = async (val: string) => {
  console.log('val', val)
  if (val) {
    state.search.orgId = val;
    await getTableData();
  }
};

// 初始化表格数据
const getTableData = async () => {
  console.log('orgId', state.search.orgId)
  state.tableData.loading = true;
  state.tableData.data = [];
  if (state.search.orgId) {
    const res = await channelTree({orgId: state.search.orgId})
    if (res.status === 200) {
      //console.log(res.data);
      state.tableData.data = res.data;
      state.tableData.loading = false;
    }
    state.tableData.total = state.tableData.data.length;
  }
};
// 打开新增菜单弹窗
const onOpenAdd = (type: string) => {

  channelDialogRef.value.openDialog(type, {});
};
// 打开编辑菜单弹窗
const onOpenEdit = (type: string, row: RowCmsChannelType) => {
  channelDialogRef.value.openDialog(type, row);
};

const onTableRowDel = (row: OrgTreeType) => {
	ElMessageBox.confirm(`确定要删除名称为：${row.label}的栏目吗？`, '提示', {
		confirmButtonText: '删除',
		cancelButtonText: '取消',
		type: 'warning',
	})
		.then( async () => {
      const res = await removeById({id:row.id})
      //console.log(res)
      if (res.status === 200) {
        ElMessage.success('删除成功');
        await getTableData();
      } else {
        ElMessage.error('删除失败');
      }

    })
		.catch(() => {});
};

// 页面加载时
onMounted(async () => {
  await loadOrgTree();
});
</script>
